// store/user.js
import { getUserInfo } from '../service/user'

// 初始状态
const state = {
  userId: '',
  nickname: '',
  avatar: '',
  phone: '',
  isLogin: false
}

// 同步修改状态
const mutations = {
  // 更新用户信息
  updateUserInfo(state, userInfo) {
    state.userId = userInfo.userId || state.userId
    state.nickname = userInfo.nickname || state.nickname
    state.avatar = userInfo.avatar || state.avatar
    state.phone = userInfo.phone || state.phone
    state.isLogin = !!userInfo.userId
  },
  
  // 退出登录
  logout(state) {
    state.userId = ''
    state.nickname = ''
    state.avatar = ''
    state.phone = ''
    state.isLogin = false
    wx.removeStorageSync('userInfo')
    wx.removeStorageSync('token')
  }
}

// 异步操作
const actions = {
  // 获取用户详情
  async getUserDetail({ commit }) {
    try {
      const res = await getUserInfo()
      commit('updateUserInfo', res.data)
      return res.data
    } catch (error) {
      console.error('获取用户信息失败', error)
      throw error
    }
  }
}

module.exports = {
  state,
  mutations,
  actions
}
